#!/usr/bin/env python3
"""
简化的启动命令接收器
使用 Flask 创建一个简单的启动命令接收服务器
"""

import json
import time
from flask import Flask, request, jsonify
from typing import Dict, Any, List

app = Flask(__name__)

# 存储接收到的启动命令
received_commands: List[Dict[str, Any]] = []


@app.route("/", methods=["GET"])
def root():
    """根路径"""
    return {
        "service": "Simple Start Command Receiver",
        "status": "running",
        "received_commands_count": len(received_commands)
    }


@app.route("/node-manager/start", methods=["POST"])
def receive_start_command():
    """
    接收启动命令
    
    这是 NodeManager 接收 Controller 发送的启动命令的端点
    """
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return jsonify({"error": "No JSON data provided"}), 400
        
        print(f"\n=== 收到启动命令 ===")
        print(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
        
        # 提取关键信息
        job_name = data.get("job_name", "unknown")
        role = data.get("role", "unknown")
        instance_id = data.get("instance_id", -1)
        endpoints = data.get("endpoints", [])
        ranktable = data.get("ranktable", {})
        
        print(f"作业名称: {job_name}")
        print(f"角色: {role}")
        print(f"实例ID: {instance_id}")
        print(f"端点数量: {len(endpoints)}")
        print(f"排名表服务器数量: {ranktable.get('server_count', 'unknown')}")
        
        # 存储命令
        command_data = {
            "timestamp": time.time(),
            "job_name": job_name,
            "role": role,
            "instance_id": instance_id,
            "endpoints_count": len(endpoints),
            "ranktable": ranktable,
            "raw_data": data
        }
        received_commands.append(command_data)
        
        # 模拟处理启动命令
        print(f"开始处理启动命令: {job_name}")
        time.sleep(0.1)  # 模拟处理时间
        print(f"启动命令处理完成: {job_name}")
        
        # 返回成功响应
        response = {
            "status": "success",
            "message": f"Start command received and processed for job {job_name}",
            "job_name": job_name,
            "instance_id": instance_id,
            "endpoints_count": len(endpoints),
            "timestamp": time.time()
        }
        
        print(f"响应: {json.dumps(response, indent=2, ensure_ascii=False)}")
        print("=" * 50)
        
        return jsonify(response)
        
    except Exception as e:
        print(f"处理启动命令时发生错误: {e}")
        return jsonify({"error": str(e)}), 500


@app.route("/node-manager/status", methods=["GET"])
def get_status():
    """获取服务器状态"""
    return {
        "status": "running",
        "received_commands": len(received_commands),
        "commands": received_commands[-5:] if received_commands else []  # 返回最近5个命令
    }


@app.route("/node-manager/commands", methods=["GET"])
def get_all_commands():
    """获取所有接收到的启动命令"""
    return {
        "total_commands": len(received_commands),
        "commands": received_commands
    }


@app.route("/node-manager/commands/<job_name>", methods=["GET"])
def get_commands_by_job(job_name: str):
    """根据作业名称获取启动命令"""
    job_commands = [cmd for cmd in received_commands if cmd["job_name"] == job_name]
    return {
        "job_name": job_name,
        "commands_count": len(job_commands),
        "commands": job_commands
    }


@app.route("/node-manager/commands", methods=["DELETE"])
def clear_commands():
    """清空所有接收到的启动命令"""
    received_commands.clear()
    return {"message": "All commands cleared"}


def main():
    """主函数"""
    print("=== 简化的启动命令接收器 ===")
    print("这个服务器模拟 NodeManager 接收来自 Controller 的启动命令")
    print("启动后，Controller 会将启动命令发送到此服务器的 /start 端点")
    print()
    print("可用的端点:")
    print("  GET  /                    - 服务器状态")
    print("  GET  /node-manager/status              - 获取状态")
    print("  POST /node-manager/start               - 接收启动命令")
    print("  GET  /node-manager/commands            - 获取所有命令")
    print("  GET  /node-manager/commands/{job_name} - 获取特定作业的命令")
    print("  DELETE /node-manager/commands         - 清空所有命令")
    print()
    print("服务器启动在: http://localhost:9090")
    print("按 Ctrl+C 停止服务器")
    print()
    
    # 启动 Flask 服务器
    app.run(host="0.0.0.0", port=9090, debug=True)


if __name__ == "__main__":
    main()
